package com.rgst.realm;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.rgst.dao.entity.SecUser;
import com.rgst.dao.repository.SecUserRepository;
import com.rgst.dao.repository.UserRoleRepository;

public class MyJdbcRealm extends AuthorizingRealm {

    @Autowired
    private SecUserRepository secUserRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    public MyJdbcRealm() {
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        SecUser secUser = secUserRepository.findByUsername(username);
        if (secUser == null) {
            throw new UnknownAccountException("No account found for user [" + username + "]");
        }
        String password = secUser.getPassword();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
        return info;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
        String username = (String) getAvailablePrincipal(principals);

        Set<String> roles = userRoleRepository.findAllRoleByUsername(username);
        Set<String> permissions = userRoleRepository.findAllPermissionByUsername(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
        info.setStringPermissions(permissions);
        return info;
    }


}
